from PyQt5.QtCore import Qt, pyqtSignal, QSize, QRectF, QPointF
from PyQt5.QtGui import QFont, QFontMetricsF, QPainter, QPalette, QColor, QPolygonF
from PyQt5.QtWidgets import QWidget, QSizePolicy, QApplication, QDialog, QLabel, QSpinBox, QLCDNumber, QGridLayout

X11 = "qt_x11_wait_for_window_manager" in dir()


class FractionSlider(QWidget):
    XMARGIN = 12.0
    YMARGIN = 5.0
    WSTRING = "999"
    valueChanged = pyqtSignal(int, int)

    def __init__(self, numerator=0, denominator=10, parent=None):
        super(FractionSlider, self).__init__(parent)
        self.__numerator = numerator
        self.__denominator = denominator
        self.setFocusPolicy(Qt.WheelFocus)
        self.setSizePolicy(QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed))

    def decimal(self):  # ok
        return self.__numerator / float(self.__denominator)

    def fraction(self):  # ok
        return self.__numerator, self.__denominator

    def sizeHint(self):  #
        return self.minimumSizeHint()

    def minimumSizeHint(self):  #
        font = QFont(self.font())
        font.setPointSize(font.pointSize() - 1)
        fm = QFontMetricsF(font)  # 参数指定字体的矩阵
        return QSize(fm.width(FractionSlider.WSTRING) * self.__denominator,
                     (fm.height() * 4) + FractionSlider.YMARGIN)

    def setFraction(self, numerator, denominator=None):
        if denominator is not None:
            if 3 <= denominator <= 60:
                self.__denominator = denominator
            else:
                raise ValueError("denominator out of range")
        if 0 <= numerator <= self.__denominator:
            self.__numerator = numerator
        else:
            raise ValueError("numberator out of range")

        self.update()
        self.updateGeometry()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.moveSlider(event.x())
            event.accept()
        else:
            QWidget.mousePressEvent(self, event)

    def mouseMoveEvent(self, event):
        self.moveSlider(event.x())

    def moveSlider(self, x):
        span = self.width() - (FractionSlider.XMARGIN * 2)  # 绘图区宽：全宽-边白*2
        offset = span - x + FractionSlider.XMARGIN  # x的坐标：区宽-x的坐标，补偿白边，其实是右边的距离
        numerator = int(round(self.__denominator * (1.0 - (offset / span))))  #
        numerator = max(0, min(numerator, self.__denominator))
        if numerator != self.__numerator:
            self.__numerator = numerator
            self.valueChanged.emit(self.__numerator, self.__denominator)

            self.update()
            self.updateGeometry()

    def keyPressEvent(self, event):
        change = 0
        if event.key() == Qt.Key_Home:
            change = -self.__denominator
        elif event.key() in (Qt.Key_Up, Qt.Key_Right):
            change = 1
        elif event.key() == Qt.Key_PageUp:
            change = (self.__denominator // 10) + 1
        elif event.key() in (Qt.Key_Down, Qt.Key_Left):
            change = -1
        elif event.key() == Qt.Key_PageDown:
            change = -((self.__denominator // 10) + 1)
        elif event.key() == Qt.Key_End:
            change = self.__denominator
        if change:
            numerator = self.__numerator
            numerator += change
            numerator = max(0, min(numerator, self.__denominator))
            if (numerator != self.__numerator):
                self.__numerator = numerator
                self.valueChanged.emit(self.__numerator, self.__denominator)
                self.update()
            event.accept()
        else:
            QWidget.keyPressEvent(self, event)

    def paintEvent(self, event=None):
        font = QFont(self.font())  # 当前字体
        font.setPointSize(font.pointSize() - 1)  # 减小1个号
        fm = QFontMetricsF(font)  # QFontMetricsF返回一个字符或字符串边缘的矩形，有宽和高的参数
        fracWidth = fm.width(FractionSlider.WSTRING)  # "999" 的宽度
        indent = fm.boundingRect("9").width() / 2.0  # “9”的宽度的一半

        if not X11:
            fracWidth *= 1.5
        span = self.width() - (FractionSlider.XMARGIN * 2)
        value = self.__numerator / float(self.__denominator)

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setRenderHint(QPainter.TextAntialiasing)
        painter.setPen(self.palette().color(QPalette.Mid))
        painter.setBrush(self.palette().brush(QPalette.AlternateBase))
        painter.drawRect(self.rect())  # 绘制大框

        segColor = QColor(Qt.green).darker(120)
        segLineColor = segColor.darker()
        painter.setPen(segLineColor)
        painter.setBrush(segColor)
        painter.drawRect(FractionSlider.XMARGIN,
                         FractionSlider.YMARGIN,
                         span, fm.height())  # 绘制绿色地带
        #
        textColor = self.palette().color(QPalette.Text)  # 文字颜色
        segWidth = span / self.__denominator  # 每段的宽度
        segHeight = fm.height() * 2  # 每段的高度
        nRect = fm.boundingRect(FractionSlider.WSTRING)  # 定制矩形，根据文字
        x = FractionSlider.XMARGIN
        yOffset = segHeight + fm.height()
        #
        for i in range(self.__denominator + 1):
            painter.setPen(segLineColor)
            painter.drawLine(x, FractionSlider.YMARGIN, x, segHeight)  # 刻度线
            painter.setPen(textColor)
            y = segHeight
            rect = QRectF(nRect)  # 绘制分数的矩形
            rect.moveCenter(QPointF(x, y + fm.height() / 2.0))  # x就在原地,y向下移动一半字高
            painter.drawText(rect, Qt.AlignCenter, str(i))  # 绘制分子
            y = yOffset  # 主值向下移动一个字高
            rect.moveCenter(QPointF(x, y + fm.height() / 2.0))  # 中心再向下移动半个字高
            painter.drawText(rect, Qt.AlignCenter, str(self.__denominator))  # 绘制分母
            painter.drawLine(QPointF(rect.left() + indent, y), QPointF(rect.right() - indent, y))  # 绘制分数线
            x += segWidth  # 向右平移

        span = int(span)
        y = FractionSlider.YMARGIN - 0.5
        triangle = [QPointF(value * span, y),
                    QPointF((value * span) + 2 * FractionSlider.XMARGIN, y),
                    QPointF((value * span) + FractionSlider.XMARGIN, fm.height())]
        painter.setPen(Qt.yellow)
        painter.setBrush(Qt.darkYellow)
        painter.drawPolygon(QPolygonF(triangle))


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    form = QDialog()
    sliderLabel = QLabel("&Fraction")
    slider = FractionSlider(denominator=12)
    sliderLabel.setBuddy(slider)
    denominatorLabel = QLabel("&Denominator")
    denominatorSpinBox = QSpinBox()
    denominatorLabel.setBuddy(denominatorSpinBox)
    denominatorSpinBox.setRange(3, 60)
    denominatorSpinBox.setValue(slider.fraction()[1])
    denominatorSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
    numeratorLabel = QLabel("Numerator")
    numeratorLCD = QLCDNumber()
    numeratorLCD.setSegmentStyle(QLCDNumber.Flat)
    layout = QGridLayout()
    layout.addWidget(sliderLabel, 0, 0)
    layout.addWidget(slider, 0, 1, 1, 5)
    layout.addWidget(numeratorLabel, 1, 0)
    layout.addWidget(numeratorLCD, 1, 1)
    layout.addWidget(denominatorLabel, 1, 2)
    layout.addWidget(denominatorSpinBox, 1, 3)
    form.setLayout(layout)


    def valueChanged(denominator):
        numerator = int(slider.decimal() * denominator)
        slider.setFraction(numerator, denominator)
        numeratorLCD.display(numerator)


    slider.valueChanged[int, int].connect(numeratorLCD.display)
    denominatorSpinBox.valueChanged[int].connect(valueChanged)
    form.setWindowTitle("Fraction Slider")
    form.show()
    app.exec_()
